﻿CREATE PROCEDURE [dbo].[CloseCashRegisterShift]
(
	@CashRegisterId int,
	@CloseUserId int,
	@Note varchar(250),
	@ShiftId int OUTPUT --идентификатор кассовой смены
)
--Закрытие кассовой смены 
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int

SET NOCOUNT ON

IF (@CashRegisterId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (@CloseUserId Is Null)
BEGIN
	SELECT @CloseUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()
	IF (@CloseUserId Is Null)
	BEGIN
		SELECT @intErrCode = 2, @strMsg = 'Не найден идентификатор для пользователя ' + suser_sname() + ' !'
		RAISERROR(@strMsg, 11, @intErrCode )
		RETURN @intErrCode
	END
END

SELECT @ShiftId = Id FROM CD.CashRegisterShifts 
WHERE CashRegisterId = @CashRegisterId AND CloseDT IS NULL
IF (@ShiftId Is Null)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Не найдена открытая смена для кассы с идентификаторм ' + cast(@CashRegisterId as varchar(10)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

UPDATE [CD].[CashRegisterShifts] SET
[CloseUserId] = @CloseUserId, [CloseDT] = getdate(), 
[Note] = IsNull(@Note,[Note]), [MD] = getdate(), [MW] = suser_sname() 
WHERE Id = @ShiftId
	
IF @@rowcount = 1 return 0
ELSE RETURN 4



